package com.sakura.system.controller.upload.image;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 批量上传文件夹图片
 */

@Slf4j
//@Controller
@RestController
@RequestMapping("/upload/files/folder/image")

public class FileFolderController {
    //    读取配置文件
    @Value("${file.upload-folder}")
//    @Value("${}")
    private String uploadBaseDir;

    @Autowired
    private HttpServletRequest request;

    // 获取文件扩展名
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }

    // 判断是否为图片文件
    private boolean isImageFile(String extension) {
        String[] allowedImageTypes = {"jpg", "jpeg", "png", "gif"};
        return Arrays.asList(allowedImageTypes).contains(extension.toLowerCase());
    }


    /**
     * 批量上传图片
     * @param folderPath
     * @return
     */
    @PostMapping("/uploadFolder")
    public List<String> uploadFolder(@RequestParam("folderPath") String folderPath) {
        // 存储上传成功的图片访问地址列表
        List<String> uploadedImageUrls = new ArrayList<>();

        // 获取目标文件夹oadedImageUrls = new ArrayList<>();

        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            return uploadedImageUrls; // 如果文件夹不存在或者不是文件夹，则直接返回空列表
        }


        // 创建同名的文件夹
        File uploadDir = new File(uploadBaseDir, folder.getName());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 获取域名或IP和端口号
        String domain;
        if (request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1")) {
            // 使用IP访问时，获取IP和端口号
            domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        } else {
            // 使用域名访问时，只获取域名
            domain = request.getScheme() + "://" + request.getServerName();
        }

        // 遍历文件夹中的每个文件
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String originalFilename = file.getName();
                String extension = getFileExtension(originalFilename);

                // 检查文件后缀是否为图片类型
                if (!isImageFile(extension)) {
                    continue; // 跳过非图片文件
                }

                try {
                    // 生成唯一的文件名
                    String filename = UUID.randomUUID().toString() + originalFilename;
                    File destFile = new File(uploadDir, filename);

                    // 将文件复制到目标文件夹
                    FileUtils.copyFile(file, destFile);

                    // 获取访问地址
                    String fileUrl = domain + "/" + uploadDir.getName() + "/" + filename;
                    uploadedImageUrls.add(fileUrl);
                } catch (IOException e) {
                    // 处理上传错误
                    e.printStackTrace();
                }
            }
        }

        return uploadedImageUrls;
    }
}
